<template>
  <div>
    <!-- 如果loading为true，则显示加载中... -->
    <div v-if="loading" class="loading">正在加载...</div>
    <div v-else>
      <!-- 如果支付成功，则显示支付完成 -->
      <div v-if="paymentSuccessful">支付完成！</div>
      
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'; 
import { useRoute ,useRouter} from 'vue-router'; 
import { payment, orderstatus } from '../../request/http';

const route = useRoute();
const router = useRouter();
const { id } = route.params;
const loading = ref(true);
const paymentSuccessful = ref(false);
const status = ref();
const url = ref('')
let statusInterval: ReturnType<typeof setInterval>;

// 检查订单状态
const checkOrderStatus = async () => {
  try {
    const res = await orderstatus(id as string);
    status.value = res.data.code;
  loading.value = true;
    // 检查支付状态
    if (status.value === 200) {
      paymentSuccessful.value = true;
       loading.value = false;
      clearInterval(statusInterval); // 停止轮询
       setTimeout(() => {
          router.push('/page')
       },5000)
    } else{
     
    }
  } catch (error) {
    console.error('获取支付状态失败:', error);
  }
};

// 初始化支付
const initiatePayment = async () => {
  loading.value = true; // 开始加载状态

  try {
    const res = await payment(id as string);
    // 这里可以根据需要处理支付逻辑
    console.log('支付请求成功:', res);
      url.value = res.data.data;
    // 跳转到支付页面
    window.open(url.value, '_blank');
    // 开始轮询检查支付状态
    statusInterval = setInterval(checkOrderStatus, 5000); // 每5秒检查一次状态
  
    // 初始状态检查
    await checkOrderStatus();
  } catch (error) {
    console.error('支付请求失败:', error);
  } finally {
    loading.value = false; // 结束加载状态
  }
};

// 组件挂载时执行支付初始化
onMounted(() => {
  initiatePayment(); // 初始化支付
});

// 组件卸载时清除轮询
onBeforeUnmount(() => {
  clearInterval(statusInterval);
});
</script>

<style scoped lang="scss">
.loading {
  text-align: center;
  font-size: 20px;
  margin-top: 50px;
}
</style>
